package com.tairan.chapter.activiti.controller;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.DeploymentEntityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/model")
public class ModelController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @GetMapping
    public Object modelList() {
        List<Model> models = repositoryService.createModelQuery().list();
        return models;
    }

    @GetMapping("deploy")
    public Object deployList() {
        List<Deployment> list = repositoryService.createDeploymentQuery().list();
        list.forEach(item -> ((DeploymentEntityImpl)item).getResources());
        return list;
    }

    @GetMapping("/re")
    public Object re() {
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
        return list;
    }

    @GetMapping("/deploy/install")
    public Object deploy(String key) {
        Map<String, Object> model = new HashMap<>();
        model.put("user", "litairan");
        ProcessInstance deployment = runtimeService.startProcessInstanceByKey(key, "1", model);
        return deployment.getDeploymentId();
    }

    @GetMapping("/task")
    public Object task() {
        List<Task> list = taskService.createTaskQuery().list();
        list.forEach(item -> System.out.println(item.getAssignee() + item.getId()));
        return list;
    }

    @GetMapping("/task/complete")
    public Object complete(String assignee) {
        List<Task> list = taskService.createTaskQuery().taskAssignee(assignee).list();
        list.forEach(item -> System.out.println(item.getId()));
        System.out.println(list.size());
        return true;
    }

    @GetMapping("/task/complete/{taskId}")
    public Object complete(@PathVariable String taskId, String assignee) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        Map<String, Object> model = new HashMap<>();
        model.put("user", "litairan");
        taskService.complete(taskId, model);
        return true;
    }
}
